import axios from "axios";
import {
	getlocalStorage,
	setlocalStorage,
} from "@/hooks/operationLocalStorage";
import singOut from "@/hooks/singOut";
import NProgress from "nprogress";
import { useStore } from "@/stores/counter";
import { ElMessage } from "element-plus";
const store = useStore();
export default function request(config: any) {
	const instance = axios.create({
		baseURL: import.meta.env.VITE_HTTP,
		withCredentials: true,
	});
	//请求拦截器
	instance.interceptors.request.use((config: any) => {
		NProgress.start();
		NProgress.inc();
		let token = getlocalStorage("token");
		config.headers["Authorization"] = token;
		return config;
	});
	//响应拦截器

	instance.interceptors.response.use((res: any) => {
		NProgress.done();
		if (res.data.code == 3001) {
			singOut(res.data.msg);
			return;
		}
		if (res.data.code && res.data.code == 4001) {
			return requestToken(config);
		} else {
			let code: number = res.status;
			if (code == 200) {
				// 导出文件需要文件名，进行判断筛选封装
				if (res.headers["content-type"].indexOf("vnd.ms-excel") > 0) {
					const str = res.headers["content-disposition"];
					const first = str.indexOf("=");
					const fileName = decodeURI(str.slice(first + 1));
					return {
						data: res.data,
						headers: res.headers["content-disposition"],
						fileName: fileName,
					};
				}
				return res.data;
			} else {
				return Promise.reject(res);
			}
		}
	});
	return instance(config);
}

/**
 * 刷新token
 * @param config
 * @returns
 */

function requestToken(config: any) {
	let refreshToken = getlocalStorage("refreshToken");
	//开始刷新token
	return request({
		url: "/refresh",
		method: "put",
		headers: { refreshToken: refreshToken },
	})
		.then((res: any) => {
			//大于4001证明需要重新登录
			if (res.code >= 4002) {
				console.log(33);

				return Promise.reject("重新登录");
			} else {
				setlocalStorage("token", res.data.accessToken);
				setlocalStorage("refreshToken", res.data.refreshToken);
				store.user.token = res.data.accessToken;
				return Promise.resolve("token刷新成功");
			}
		})
		.then(
			(res) => {
				//token刷新完后重新发送上一次请求
				return request({
					url: config.url,
					method: config.method,
					body: config.body,
				});
			},
			(err) => {
				singOut("账号过期请重新登录");
				return Promise.reject(err);
			}
		);
}
